/*
 * panelTowerInfo.java
 *
 * Created on November 26, 2007, 8:57 PM
 *
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package hextd.UI;

import hextd.HexTD;
import hextd.sprite.EnemySprite;
import hextd.sprite.EnemySpriteChangedListener;
import hextd.tower.PanelTowerSettings;
import hextd.tower.Tower;
import hextd.util.Context;
import hextd.util.ContextListener;
import hextd.util.TowerChangeListener;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

/**
 *
 * @author  hylke
 */
public class PanelTowerInfo extends javax.swing.JPanel implements ContextListener, TowerChangeListener, EnemySpriteChangedListener {

	public static DecimalFormat form = new DecimalFormat("#,###.#");
	private Context context;
	private Tower selectedTower;
	private EnemySprite selectedCreep;
	private HTMLEditorKit editorkit;
	private boolean selling = false;
	private PanelTowerSettings pts;

	/** Creates new form panelTowerInfo */
	public PanelTowerInfo() {
	}

	public void setContext(Context context) {
		this.context = context;
		this.context.addContextListener(this);

		this.editorkit = new HTMLEditorKit();

		initComponents();

		this.jButton_confirmN.setVisible(false);
		this.jButton_confirmY.setVisible(false);
		this.jLabel_buttons.setVisible(false);

		StyleSheet s = this.context.loadStyleSheet("styles.css");
		this.editorkit.setStyleSheet(s);
		this.jTextPane1.setEditorKit(this.editorkit);
	}

	public void setTower(Tower t) {
		this.unselectCreep();
		this.selling = false;
		synchronized (this) { // this.selectedTower can be unselected by the other thread.

			if (this.selectedTower != null) {
				this.selectedTower.setSelected(false);
				this.selectedTower.removeTowerChangeListener(this);
			}
			this.selectedTower = t;
			this.selectedTower.setSelected(true);
			this.selectedTower.addTowerChangeListener(this);
		}
		this.jPanel_towerSettings.removeAll();
		this.pts = t.getButtons();
		if (this.pts != null) {
			this.jPanel_towerSettings.add(this.pts);
		}
		this.setVisible(true);
		this.updateInterface();
	}

	public void setCreep(EnemySprite s) {
		this.unselectTower();
		this.unselectCreep();
		this.selectedCreep = s;
		s.addStatusListener(this);
		s.setSelected(true);
		this.setText(s.getStatusString());
		this.setVisible(true);
	}

	public void setExternalText(String s) {
		this.unselectCreep();
		this.unselectTower();
		this.selling = false;
		this.jPanel_buttons.setVisible(false);
		this.jPanel_towerSettings.removeAll();
		this.setText(s);
		this.setVisible(true);
	}

	private String format(int number) {
		if (number > 1000) {
			return PanelTowerInfo.form.format(1f * number / 1000) + "K";
		} else {
			return "" + number;
		}
	}

	private void updateInterface() {
		if (this.selectedCreep != null) {
		} else {
			this.jPanel_buttons.setVisible(false);
			if (context.gameState == HexTD.gameState.playing) {
				if (this.selling) {
					this.jButton_sell.setVisible(false);
					this.jButton_upgrade.setVisible(false);
					this.jButton_confirmN.setVisible(true);
					this.jButton_confirmY.setVisible(true);
					this.jLabel_buttons.setVisible(true);
				} else {
					this.jButton_confirmN.setVisible(false);
					this.jButton_confirmY.setVisible(false);
					this.jLabel_buttons.setVisible(false);
					this.jButton_sell.setVisible(true);
					this.jButton_upgrade.setVisible(true);
				}
				synchronized (this) { // this.selectedTower can be unselected by the other thread.

					if (this.selectedTower != null) {
						if (this.pts != null) {
							this.pts.setEnabled(true);
						}
						this.jPanel_buttons.setVisible(true);
						if (this.selectedTower.canUpgrade() &&
								this.context.canPay(this.selectedTower.getUpgradePrice())) {
							this.jButton_upgrade.setEnabled(true);
						} else {
							this.jButton_upgrade.setEnabled(false);
						}
						this.jButton_upgrade.setText(" ↥ (" + format(this.selectedTower.getUpgradePrice()) + "€)");
						this.jButton_sell.setText(" ↺ (" + format(this.selectedTower.getSellPrice()) + "€)");
						this.setText(this.selectedTower.getStatusString());
					}
				}
			} else {
				synchronized (this) { // this.selectedTower can be unselected by the other thread.

					if (this.selectedTower != null) {
						this.setText(this.selectedTower.getStatusString());
						if (this.pts != null) {
							this.pts.setEnabled(false);
						}
					}
				}
			}
		}
	}

	private synchronized void setText(String s) {
		try {
			Document doc = this.jTextPane1.getDocument();
			doc.remove(0, doc.getLength());
			this.jTextPane1.setText("<html><body>" + s + "</body></html>");
		} catch (BadLocationException ex) {
			Logger.getLogger(PanelTowerInfo.class.getName()).log(Level.SEVERE, null, ex);
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	public void unselectTower() {
		synchronized (this) { // this.selectedTower can be unselected by the other thread.

			this.setVisible(false);
			if (this.selectedTower != null) {
				this.selectedTower.setSelected(false);
				this.selectedTower.removeTowerChangeListener(this);
			}
			this.selectedTower = null;
		}
		this.jPanel_towerSettings.removeAll();
	}

	public void unselectCreep() {
		if (this.selectedCreep != null) {
			this.selectedCreep.removeStatusListener(this);
			this.selectedCreep.setSelected(false);
			this.selectedCreep = null;
		}
	}

	public void upgradeCurrentTower(boolean fully) {
		// Check money
		synchronized (this) { // this.selectedTower can be unselected by the other thread.
			if (fully) {
				if (this.selectedTower != null) {
					int[] hexC = this.selectedTower.getHex().getLocation();
					while (this.selectedTower.canUpgrade() && this.context.canPay(this.selectedTower.getUpgradePrice())) {
						this.context.blackBoxCurrent.upgradeTower(hexC[0], hexC[1]);
					}
				}
			} else {
				if (this.selectedTower != null && this.selectedTower.canUpgrade()) {
					int[] hexC = this.selectedTower.getHex().getLocation();
					this.context.blackBoxCurrent.upgradeTower(hexC[0], hexC[1]);
				}
			}
		}
	}

	public void startSellCurrentTower() {
		synchronized (this) { // this.selectedTower can be unselected by the other thread.

			if (this.selectedTower != null && context.gameState == HexTD.gameState.playing) {
				this.selling = true;
				this.updateInterface();
			}
		}
	}

	public void confirmSell() {
		synchronized (this) { // this.selectedTower can be unselected by the other thread.

			if (this.selling && this.selectedTower != null && context.gameState == HexTD.gameState.playing) {
				this.context.sellTower(this.selectedTower);
				this.selling = false;
				this.unselectTower();
				this.updateInterface();
			}
		}
	}

	public void cancelSell() {
		this.selling = false;
		this.updateInterface();
	}

	@Override
	public void moneyChanged() {
		this.updateInterface();
	}

	@Override
	public void livesChanged() {
	}

	@Override
	public void interestChanged() {
	}

	public void nextMode(int m) {
		if (this.selectedTower != null) {
			this.context.nextMode(this.selectedTower, m);
		}
	}

	@Override
	public void towerChanged() {
		this.updateInterface();
	}

	@Override
	public void enemySpriteStatusChanged() {
		this.setText(this.selectedCreep.getStatusString());
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jPanel_towerSettings = new javax.swing.JPanel();
        jPanel_buttons = new javax.swing.JPanel();
        jButton_upgrade = new javax.swing.JButton();
        jButton_sell = new javax.swing.JButton();
        jButton_confirmY = new javax.swing.JButton();
        jLabel_buttons = new javax.swing.JLabel();
        jButton_confirmN = new javax.swing.JButton();

        setBackground(this.context.colors.getColorBackGround());
        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Bitstream Vera Sans", 0, 13), this.context.colors.getColorForeGround()));
        setForeground(this.context.colors.getColorForeGround());
        setMaximumSize(new java.awt.Dimension(200, 2147483647));
        setMinimumSize(new java.awt.Dimension(200, 150));
        setPreferredSize(new java.awt.Dimension(200, 300));
        setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setBackground(this.context.colors.getColorBackGround());
        jScrollPane1.setBorder(null);
        jScrollPane1.setForeground(this.context.colors.getColorForeGround());

        jTextPane1.setBackground(this.context.colors.getColorBackGround());
        jTextPane1.setBorder(null);
        jTextPane1.setForeground(this.context.colors.getColorForeGround());
        jScrollPane1.setViewportView(jTextPane1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.01;
        gridBagConstraints.weighty = 0.01;
        add(jScrollPane1, gridBagConstraints);

        jPanel_towerSettings.setBackground(this.context.colors.getColorBackGround());
        jPanel_towerSettings.setForeground(this.context.colors.getColorForeGround());
        jPanel_towerSettings.setLayout(new java.awt.BorderLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        add(jPanel_towerSettings, gridBagConstraints);

        jPanel_buttons.setBackground(this.context.colors.getColorBackGround());
        jPanel_buttons.setForeground(this.context.colors.getColorForeGround());
        jPanel_buttons.setLayout(new java.awt.GridBagLayout());

        jButton_upgrade.setBackground(this.context.colors.getColorBackGround());
        jButton_upgrade.setForeground(this.context.colors.getColorForeGround());
        jButton_upgrade.setText(" ↥ ");
        jButton_upgrade.setToolTipText("Upgrade");
        jButton_upgrade.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jButton_upgrade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_upgradeActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.weightx = 0.01;
        jPanel_buttons.add(jButton_upgrade, gridBagConstraints);

        jButton_sell.setBackground(this.context.colors.getColorBackGround());
        jButton_sell.setForeground(this.context.colors.getColorForeGround());
        jButton_sell.setText("↺");
        jButton_sell.setToolTipText("Recycle");
        jButton_sell.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jButton_sell.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_sellActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 0.01;
        jPanel_buttons.add(jButton_sell, gridBagConstraints);

        jButton_confirmY.setBackground(this.context.colors.getColorBackGround());
        jButton_confirmY.setForeground(this.context.colors.getColorForeGround());
        jButton_confirmY.setText("Y");
        jButton_confirmY.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_confirmYActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        jPanel_buttons.add(jButton_confirmY, gridBagConstraints);

        jLabel_buttons.setBackground(this.context.colors.getColorBackGround());
        jLabel_buttons.setForeground(this.context.colors.getColorForeGround());
        jLabel_buttons.setText("Confirm sale:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.weightx = 0.02;
        jPanel_buttons.add(jLabel_buttons, gridBagConstraints);

        jButton_confirmN.setBackground(this.context.colors.getColorBackGround());
        jButton_confirmN.setForeground(this.context.colors.getColorForeGround());
        jButton_confirmN.setText("N");
        jButton_confirmN.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_confirmNActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        jPanel_buttons.add(jButton_confirmN, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        add(jPanel_buttons, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents
    private void jButton_confirmYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_confirmYActionPerformed
		this.confirmSell();
    }//GEN-LAST:event_jButton_confirmYActionPerformed

    private void jButton_confirmNActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_confirmNActionPerformed
		this.cancelSell();
    }//GEN-LAST:event_jButton_confirmNActionPerformed

    private void jButton_sellActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_sellActionPerformed
		this.startSellCurrentTower();
    }//GEN-LAST:event_jButton_sellActionPerformed

    private void jButton_upgradeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_upgradeActionPerformed
		this.selling = false;
		this.upgradeCurrentTower(false);
    }//GEN-LAST:event_jButton_upgradeActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_confirmN;
    private javax.swing.JButton jButton_confirmY;
    private javax.swing.JButton jButton_sell;
    private javax.swing.JButton jButton_upgrade;
    private javax.swing.JLabel jLabel_buttons;
    private javax.swing.JPanel jPanel_buttons;
    private javax.swing.JPanel jPanel_towerSettings;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables
}
